package com.lsh.payment.service.payment;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.lsh.payment.api.model.basevo.*;
import com.lsh.payment.api.model.payment.PaymentQueryCheckRequest;
import com.lsh.payment.api.model.payment.PaymentQueryRequest;
import com.lsh.payment.api.service.payment.IPayQueryRestService;
import com.lsh.payment.core.exception.BusinessException;
import com.lsh.payment.core.model.payenum.PayChannel;
import com.lsh.payment.core.model.payment.PayDeal;
import com.lsh.payment.core.service.payment.impl.PayQueryBaseService;
import com.lsh.payment.core.util.Criteria;
import com.lsh.payment.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

/**
 * Project Name: lsh-payment
 *
 * @author miaozhuang
 * @date 16/11/7
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service(protocol = "rest", validation = "true")
@Path("payment")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8})
public class PayQueryRestService extends BaseService implements IPayQueryRestService {

    private final Logger logger = LoggerFactory.getLogger(PayQueryRestService.class);

    @Autowired
    private PayQueryBaseService payQueryBaseService;

    @Override
    @POST
    @Path("query")
    public BaseResponse queryPayStatus(PaymentQueryRequest paymentQueryRequest) {

        QueryResponse queryResponse = new QueryResponse();

        long beginTime = System.currentTimeMillis();
        try {

            logger.info("统一查询接口参数 {}", JSON.toJSONString(paymentQueryRequest));

            QueryContent content = payQueryBaseService.queryPayStatus(paymentQueryRequest);
            queryResponse.setContent(content);

            queryResponse.setRet(Integer.parseInt(ExceptionStatus.SUCCESS.getCode()));
            queryResponse.setMsg(ExceptionStatus.SUCCESS.getMessage());

        } catch (BusinessException e) {

            queryResponse.setRet(Integer.parseInt(e.getCode()));
            queryResponse.setMsg(e.getMessage());
            logger.error("业务异常, code {}, message {}.", e.getCode(), e.getMessage());
        } catch (Exception e) {

            queryResponse.setRet(Integer.parseInt(ExceptionStatus.E3001001.getCode()));
            queryResponse.setMsg(ExceptionStatus.E3001001.getMessage());
            logger.error("服务端异常", e);
        }

//        try {
//            long wasteTime = System.currentTimeMillis() - beginTime;
//            logger.info("统一查询接口耗时 {} 毫秒。", wasteTime);
//            String wasteTimeStr = (new StringBuffer(DateUtil.nowStrFormate())).append("[").append(wasteTime).append("]").toString();
//            PayMonitorInterfaceModel payMonitorInterfaceModel = new PayMonitorInterfaceModel(paymentQueryRequest, wasteTimeStr, this.getClass().getSimpleName());
//            if (!queryResponse.getRet().toString().equals(ExceptionStatus.SUCCESS.getCode())) {
//                payMonitorInterfaceModel.setResultFlag(false);
//            }
//            PayEventBus.post(payMonitorInterfaceModel);
//        } catch (Throwable e) {
//            logger.error("收集监控信息失败", e);
//        }

        return queryResponse;
    }


    @Override
    @POST
    @Path("paydealinfo")
    public BaseResponse queryPayDeal(PaymentQueryRequest paymentQueryRequest) {

        PayDealQueryResponse queryResponse = new PayDealQueryResponse();
        try {

            logger.info("payDeal统一查询接口参数 {}", JSON.toJSONString(paymentQueryRequest));
            PayDeal payDeal = payQueryBaseService.queryPayDeal(paymentQueryRequest);

            BeanUtils.copyProperties(payDeal, queryResponse);
            PayChannel payChannel = PayChannel.getPayChannel(payDeal.getPayChannel());
            queryResponse.setPayChannelType(payChannel.getCode());

            queryResponse.setRet(Integer.parseInt(ExceptionStatus.SUCCESS.getCode()));
            queryResponse.setMsg(ExceptionStatus.SUCCESS.getMessage());

        } catch (BusinessException e) {
            queryResponse.setRet(Integer.parseInt(e.getCode()));
            queryResponse.setMsg(e.getMessage());
            logger.error("业务异常, code {}, message {}.", e.getCode(), e.getMessage());
        } catch (Exception e) {
            queryResponse.setRet(Integer.parseInt(ExceptionStatus.E3001001.getCode()));
            queryResponse.setMsg(ExceptionStatus.E3001001.getMessage());
            logger.error("服务端异常", e);
        }

        return queryResponse;
    }

    @GET
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public CommonResult query(@Context UriInfo uriInfo,
                              @DefaultValue("1") @QueryParam("page") long page,
                              @DefaultValue("20") @QueryParam("page-limit") long limit) {
        return CommonResult.success(payQueryBaseService.query(Criteria.of(uriInfo), page, limit));
    }




    @POST
    @Produces({MediaType.APPLICATION_JSON})
    @Path("queryCheck")
    @Override
    public CommonResult queryCheck(PaymentQueryCheckRequest paymentQueryCheckRequest) {
        Long venderId = paymentQueryCheckRequest.getVender_id();
        if(venderId == null){
            paymentQueryCheckRequest.setVender_id(this.getVenderId());
        }
        return CommonResult.success(payQueryBaseService.queryCheck(paymentQueryCheckRequest));
    }
}
